package cn.fz.luck.saas.config.security;

import cn.fz.luck.saas.config.security.jwt.JwtUserFactory;
import cn.fz.luck.saas.mapper.SysUserMapper;
import cn.fz.luck.saas.model.SysPermission;
import cn.fz.luck.saas.model.SysUser;
import cn.fz.luck.saas.service.SysPermissionService;
import cn.fz.luck.saas.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhuangqi on 17-7-6.
 */
@Service
public class CustomUserService implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        SysUser user = null;
        try {
            user = sysUserService.getByUserName(userName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(user.getUserName());
        if (user == null) new UsernameNotFoundException("admin: " + userName + " do not exist!");

        List<SysPermission> permissions = sysPermissionService.listByUserId(user.getUserId());
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (SysPermission permission : permissions) {
            if (permission != null && permission.getPermissonName() != null) {
                GrantedAuthority grantedAuthority = new CustomGrantedAuthority(permission.getUrl(), permission.getMethod());
                grantedAuthorities.add(grantedAuthority);
            }
        }
        return JwtUserFactory.create(user,grantedAuthorities);
    }
}
